package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ClassName: AuthorizeFilter
 * Description: 授权过滤器
 * date: 2023/8/5 0005 15:49
 *
 * @author zHan
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    /**
     * @param exchange
     * @param chain
     * @return
     */
    @Order(0)    // 值越小，优先级越高
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 判断是否是登录请求
        if (request.getURI().getPath().contains("/login")) {
            // 放行
            return chain.filter(exchange);
        }
        // 获取token
        String token = request.getHeaders().getFirst("token");
        // 判断是否有token，没有token
        if (StringUtils.isBlank(token)) {
            // 返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 判断token是否有效
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            // token过期
            if (verifyToken == 1 || verifyToken == 2) {
                // 返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            // 获取用户id
            Object userId = claims.get("id");
            // 添加到请求头
            ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", String.valueOf(userId));
            }).build();
            // 重置请求
            exchange.mutate().request(httpRequest);
        } catch (Exception e) {
            // 解析失败，返回401
            e.printStackTrace();
            // 返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 放行
        return chain.filter(exchange);
    }
}
